import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ymt/api/apis.dart';
import 'package:ymt/model/product.dart';
import 'package:ymt/utils/image.dart';
import 'package:ymt/utils/request.dart';

import 'preview.dart';

class RecommendProductsPage extends StatelessWidget{
  final int _productId;

  const RecommendProductsPage(this._productId);
  @override
  Widget build(BuildContext context) {
    MyHome home = MyHome(_productId);
    return MaterialApp(theme: new ThemeData.dark(), home: Scaffold(
      appBar: AppBar(title: _buildBackText(context),
        elevation: 0,), body: home,),);
  }

  _buildBackText(context) {
    return click(Row(children: <Widget>[
      Icon(Icons.arrow_back_ios),
      Expanded(child: Text("同品牌推荐", style: TextStyle(fontSize: 15)),)
    ],), ()=>Navigator.pop(context));
  }

  Widget click(child, onTap) {
    return GestureDetector(child: child, onTap: onTap,);
  }
}

class MyHome extends StatefulWidget{

  MyHomeState state;

  final int _productId;

  MyHome(this._productId);

  @override
  State<StatefulWidget> createState() {
    state = MyHomeState(_productId);
    return state;
  }
}

class MyHomeState extends State<MyHome>{

  var _products = <Product>[];
  bool isLoadComplete;
  var _pageIndex = 1;
  Dio dio;
  final _productId;

  MyHomeState(this._productId);

  @override
  void initState() {
    initDio();
    getProducts({
      "id": _productId,
      "page": _pageIndex
    });
    super.initState();
  }

  void initDio(){
    dio = Request.dio();
  }

  @override
  Widget build(BuildContext context) {
    return _buildGrid();
  }
  Widget _buildGrid() {
    return new GridView.builder(
      padding: EdgeInsets.only(left: 22, right: 22,),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
          crossAxisCount: 4,
          childAspectRatio: 16 / 9),
      itemBuilder: (context, position) {
        if (_products != null && _products.isNotEmpty) {
          if (position == _products.length) {
            //分页加载
            _pageIndex++;
            getProducts({
              "id": _productId,
              "page": _pageIndex
            });
          }
          if (position < _products.length) {
            return _buildImage(_products[position].main_picture, position);
          }
        }
        return Container();
      }, itemCount: _products.length + 1,
      physics: BouncingScrollPhysics(),
    );
  }

  Widget _buildImage(img, position){
    return CacheImage.imageClickToDetails(context, img, _products, position);
  }

  void getProducts(params) async {
    try{
      isLoadComplete = false;
      var response = await dio.get(ApiPaths.SAME_SOURCE_PRODUCTS, queryParameters: params);
      List<Product> list = List<Product>.from(response.data.map((e) => Product.fromJson(e)).toList());
      var page = params["page"];
      if(list.isNotEmpty) {
        // 返回了数据则追加数据，刷新UI
        setState(() {
          _products.addAll(list);
        });
      }else{
        // 如果第一页数据为空，并且当前有数据则清空产品列表
        if (page <= 1) {
          if(_products.isNotEmpty){
            print("请求第$page页，返回${_products.length}条数据");
            setState(() {
              _products.clear();
            });
          }
        }

      }
    }catch(e){
      print(e);
    }
  }

}